<template>
  <div class="machine-daily-profit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>每日总机台盈利</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>
    
    <div class="filter-row">
      <el-form :inline="true" :model="filterForm" size="small">
        <el-form-item label="渠道">
          <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户标签">
          <el-input v-model="filterForm.user_tag" placeholder="请输入用户标签" type="number" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 240px;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="headerCellStyle"
      v-loading="loading"
    >
      <!-- 日期列 -->
      <el-table-column prop="create_time" label="日期" width="110" align="center"></el-table-column>
      
 
      <!-- 总玩金币 -->
      <el-table-column prop="total_play" label="总玩" align="center" width="120"></el-table-column>
      
      <!-- 总赢金币 -->
      <el-table-column prop="total_win" label="总赢" align="center" width="120"></el-table-column>
      
      <!-- 总玩-总赢 -->
      <!-- 总RTP -->
      <el-table-column prop="total_rtp" label="RTP" align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.total_rtp !== null && scope.row.total_rtp !== undefined && scope.row.total_rtp !== '' ? scope.row.total_rtp + '%' : '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="total_diff" label="总玩-总赢差值" align="center" width="160"></el-table-column>
      
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    </el-card>
  </div>
</template>

<script>
import { gameDayList } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'MachineDailyProfit',
  mixins: [channelMixin],
  data() {
    return {
      dateRange: [],
      tableData: [],
      loading: false,
      exportLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filterForm: {
        channel: null,
        user_tag: '',
        dateRange: []
      }
    };
  },
  created() {
    // 设置默认日期为最近7天
    const today = new Date()
    const lastWeek = new Date()
    lastWeek.setDate(today.getDate() - 7)
    this.filterForm.dateRange = [
      lastWeek.toISOString().split('T')[0],
      today.toISOString().split('T')[0]
    ]
    // 渠道选项通过mixin自动加载
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          user_tag: this.filterForm.user_tag ? parseInt(this.filterForm.user_tag) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : '',
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        console.log('===== MachineDailyProfit Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await gameDayList(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          console.log('接口成功，response.data:', response.data)
          console.log('response.data的类型:', typeof response.data)
          console.log('response.data的结构:', Object.keys(response.data || {}))
          
          // 根据接口文档，gameDayList返回game_days数组
          let records = []
          if (response.data && response.data.game_days && Array.isArray(response.data.game_days)) {
            records = response.data.game_days
            console.log('使用 response.data.game_days')
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用 response.data.records')
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用 response.data.list')
          } else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用 response.data 直接数组')
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用 response.data.data')
          } else {
            console.log('未找到数组数据，尝试遍历所有属性:')
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                console.log(`response.data.${key}:`, response.data[key], 'isArray:', Array.isArray(response.data[key]))
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`找到数组数据在 response.data.${key}`)
                  break
                }
              }
            }
          }
          
          console.log('解析后的records:', records)
          console.log('records长度:', records.length)
          console.log('records第一条数据:', records[0])
          
          // 强制设置数据并触发视图更新
          this.tableData = [...records]
          
          // 处理总数
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else if (response.total_page) {
            this.total = response.total_page * this.pageSize
          } else if (response.total) {
            this.total = response.total
          } else {
            this.total = records.length
          }
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('当前tableData:', this.tableData)
          console.log('设置total:', this.total)
          
          // 强制Vue重新渲染
          this.$nextTick(() => {
            this.$forceUpdate()
            console.log('强制更新完成，当前tableData:', this.tableData)
          })
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取每日机台盈利数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          user_tag: this.filterForm.user_tag ? parseInt(this.filterForm.user_tag) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : '',
          page: 1,
          page_size: 10000
        }
        
        const response = await gameDayList(params)
        const allData = response.data.game_days || []
        
        const columns = [
          { prop: 'create_time', label: '日期' },
          { prop: 'total_play', label: '总玩' },
          { prop: 'total_win', label: '总赢' },
          { prop: 'total_diff', label: '总玩-总赢差值' },
          { prop: 'total_rtp', label: '总RTP', formatter: (row) => (row.total_rtp !== null && row.total_rtp !== undefined && row.total_rtp !== '') ? row.total_rtp + '%' : '--' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `每日总机台盈利_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    headerCellStyle() {
      return {
        backgroundColor: '#e6f1fc',
        color: '#333',
        fontWeight: '600',
        padding: '8px',
        textAlign: 'center'
      };
    },
    resetFilter() {
      this.filterForm.channel = null
      this.filterForm.user_tag = ''
      this.filterForm.dateRange = []
      this.currentPage = 1
      this.fetchData()
    }
  }
};
</script>

<style scoped>
.machine-daily-profit {
  width: 100%;
}

.page-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  display: none; /* 隐藏标题，由于表格上方有标题 */
}

.filter-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-table th {
  background-color: #e6f1fc;
  padding: 8px 0;
}

::v-deep .el-table td {
  padding: 8px 0;
}

::v-deep .el-table .cell {
  word-break: normal;
  white-space: nowrap;
}

::v-deep .el-table--border th, 
::v-deep .el-table--border td {
  border-right: 1px solid #dcdfe6;
}
</style>